package com.vcommon.core.modules
{
import com.vcommon.core.loaderqueue.LoaderQueueEvent;
import com.vcommon.core.loaderqueue.adapter.URLLoaderAdapter;
import com.vcommon.core.logging.Tracer;

import flash.display.Loader;
import flash.events.Event;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.SecurityDomain;
import flash.utils.ByteArray;

/**
 * 加密swf的模块加载代码
 * @author waitingsnow
 * $Id:$
 */
public class ModuleEncodeInfo extends AbstractModuleInfo implements IModuleInfo
{
    //==========================================================================
    //  Constructor
    //==========================================================================
    /**
     * Constructs a new <code>ModuleEncodeInfo</code> instance.
     *
     */
    public function ModuleEncodeInfo(moduleName:String, skinDir:String)
    {
        super(moduleName, skinDir);
    }

    //==========================================================================
    //  Variables
    //==========================================================================
    private var mainParser:Loader;


    //==========================================================================
    //  Properties
    //==========================================================================

    private var _suffix:String = ".png";
    /**
     * 加密后缀
     */
    public function set suffix(value:String):void
    {
        _suffix = value;
    }

    //==========================================================================
    //  Methods
    //==========================================================================

    override public function load(applicationDomain:ApplicationDomain=null,
                         securityDomain:SecurityDomain=null,
                         bytes:ByteArray=null,
                         level:uint = 0):void
    {
        super.load(applicationDomain, securityDomain, bytes, level);

        var url:String = moduleVO.url;
        url = url.replace(".swf", _suffix);
        var urlRequest:URLRequest = new URLRequest(url);
        mainLoader = new URLLoaderAdapter(level, urlRequest);
        URLLoaderAdapter(mainLoader).dataFormat = URLLoaderDataFormat.BINARY;
        mainLoader.addEventListener(LoaderQueueEvent.TASK_COMPLETED,
            mainLoader_completedHandler);
        mainLoader.addEventListener(LoaderQueueEvent.TASK_ERROR,
            mainLoader_errorHandler);
        mainLoader.addEventListener(LoaderQueueEvent.TASK_PROGRESS,
            mainLoader_progressHandler);
        Tracer.debug("[Module] loading encode module : " + urlRequest.url);
        loaderQueue.addItem(mainLoader);
    }

    /**
     * 解密代码
     * @param byteArr
     *
     */
    private function unEncript(data:ByteArray):ByteArray
    {
        var result:ByteArray = new ByteArray();
        var p:int = 0x63;
        var s1:ByteArray = new ByteArray();
        data.readBytes(s1, 0, data.bytesAvailable - p);
        var s2:ByteArray = new ByteArray();
        data.readBytes(s2, 0, data.bytesAvailable);
        result.writeByte(0x43);
        result.writeByte(0x57);
        result.writeByte(0x53);
        result.writeByte(0x0A);
        result.writeBytes(s2);
        result.writeBytes(s1);
        return result;
    }

    override protected function clearLoader():void
    {
        super.clearLoader();
        if (mainParser)
        {
            mainParser.contentLoaderInfo.removeEventListener(Event.COMPLETE,
                parser_completeHandler);
            mainParser.unloadAndStop();
            mainParser = null;
        }
    }

    //==========================================================================
    //  Event Handlers
    //==========================================================================

    override protected  function mainLoader_completedHandler(event:LoaderQueueEvent):void
    {
        var byteArr:ByteArray = unEncript(URLLoaderAdapter(mainLoader).adaptee.data);
        mainParser = new Loader();
        mainParser.contentLoaderInfo.addEventListener(Event.COMPLETE,
            parser_completeHandler);
        mainParser.loadBytes(byteArr, loaderContext);
    }

    /**
     * 解密完成后触发
     * @param event
     *
     */
    protected  function parser_completeHandler(event:Event):void
    {
        _applicationDomain = mainParser.contentLoaderInfo.applicationDomain;
        _factoy = new ModuleFactory(_applicationDomain, moduleVO);
        clearLoader();
        _ready = true;

        startLoadSkin();
    }
}
}